package com.my.test.thread.concurrent;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExchangerDemo  {

    // 只能用于2个线程之间交换数据,没有交换的会阻塞
    static final Exchanger<String> ex = new Exchanger<>();

    static ExecutorService es = Executors.newFixedThreadPool(3);

    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            String a = "銀行流水a";
            try {
                String sss = ex.exchange(a);
                System.out.println("t1:"+sss);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread t2 = new Thread(()->{
            String b = "銀行流水b";
            try {
                String s = ex.exchange(b);
                System.out.println("t2："+s);
                System.out.println("a和b录入的是否一致:"+s.equals(b));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        /*Thread t3 = new Thread(()->{
            String c = "銀行流水c";
            try {
                String cc = ex.exchange(c);
                System.out.println("t3："+cc);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });*/
        es.execute(t1);
        es.execute(t2);
        //es.execute(t3);
        es.shutdown();

    }

}
